package com.hengxinguotong.zhihuichengjian.ui.building;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.BuildListAdapter;
import com.hengxinguotong.zhihuichengjian.adapter.EnterpriseBuildListAdapter;
import com.hengxinguotong.zhihuichengjian.bean.Build;
import com.hengxinguotong.zhihuichengjian.bean.BuildListRes;
import com.hengxinguotong.zhihuichengjian.bean.MenuBean;
import com.hengxinguotong.zhihuichengjian.bean.MenuListRes;
import com.hengxinguotong.zhihuichengjian.ui.BaseActivity;
import com.hengxinguotong.zhihuichengjian.utils.Constants;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXEditTextView;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.hengxinguotong.zhihuichengjian.widget.view.PullableRecyclerView;
import com.jingchen.pulltorefresh.PullToRefreshLayout;
import com.lidroid.xutils.http.RequestParams;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 建设管理列表
 *
 * @CopyRight 恒信国通信息科技
 * @Author WuLei
 * @Date 2018/12/24
 */

public class BuildListActivity extends BaseActivity implements View.OnClickListener
{
    private static final String TAG = "QualityListActivity";
    @BindView(R.id.title_tv)
    HXTextView titleTv;
    @BindView(R.id.iv_back)
    HXTextView ivBack;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.add)
    HXTextView add;
    @BindView(R.id.search_rl)
    RelativeLayout searchRl;
    @BindView(R.id.et_project)
    HXEditTextView etProject;
    @BindView(R.id.refresh_list)
    PullToRefreshLayout refreshList;

    private PullableRecyclerView dataRv;

    private BuildListAdapter buildListAdapter;
    private EnterpriseBuildListAdapter eBuildListAdapter;
    private int type = Constants.LIVE;//现场管理
    private String title;//
    private int pageIndex = 1;
    private List<Build> buildList;
    private List<MenuBean> menuList;//

    private Handler handler = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            switch (msg.what)
            {
                case Constants.UPDATE:
                    List<Build> datas = (List<Build>) msg.obj;
                    addBuildData(datas);
                    break;
            }
        }
    };
    private boolean fromEnterprise = false;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_quality);
        ButterKnife.bind(this);
        type = getIntent().getIntExtra("type", Constants.LIVE);
        title = getIntent().getStringExtra("title");
        fromEnterprise = getIntent().getBooleanExtra("fromEnterprise", false);
        initView();
        initData();
    }

    private void initView()
    {
        titleTv.setText(title);
        if (fromEnterprise)
        {
            searchRl.setVisibility(View.VISIBLE);
            etProject.addTextChangedListener(textWatcher);
        } else
        {
            searchRl.setVisibility(View.GONE);
        }
        String authority = SPUtil.getString(this, "authority");
        if (!Utils.isEmpty(authority))
        {
            try
            {
                MenuListRes menuListRes = new Gson().fromJson(authority, MenuListRes.class);
                menuList = menuListRes.getValue();
            } catch (Exception e)
            {
                Log.e(TAG, e.getMessage().toString());
            }
        }
        if (menuList == null)
        {
            menuList = new ArrayList<>();
        }
        add.setVisibility(View.GONE);
        for (MenuBean menu : menuList)
        {
            if (menu.getId() == 1500)
            {
                for (MenuBean sMenu : menu.getData())
                {
                    if (sMenu.getId() == 1510)
                    {
                        if (sMenu.getAuth().getAdd() == 1)
                        {
                            add.setVisibility(View.VISIBLE);
                        }
                    }
                }
            }
        }
        refreshList.setPullUpEnable(false);
        refreshList.setOnPullListener(pullListener);
        dataRv = (PullableRecyclerView) refreshList.getPullableView();
        buildList = new ArrayList<>();
        if (fromEnterprise)
        {
            eBuildListAdapter = new EnterpriseBuildListAdapter(this, buildList);
            eBuildListAdapter.setClickListener(eClickListener);
            dataRv.setAdapter(eBuildListAdapter);
        } else
        {
            buildListAdapter = new BuildListAdapter(this, buildList);
            buildListAdapter.setClickListener(clickListener);
            dataRv.setAdapter(buildListAdapter);
        }
        dataRv.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));

    }

    private void initData()
    {
        handler.postDelayed(new Runnable()
        {
            @Override
            public void run()
            {
                getBuildList("搜索中…");
            }
        }, 500);
    }

    private PullToRefreshLayout.OnPullListener pullListener = new PullToRefreshLayout.OnPullListener()
    {
        @Override
        public void onRefresh(PullToRefreshLayout pullToRefreshLayout)
        {
            pageIndex = 1;
            initData();
        }

        @Override
        public void onLoadMore(PullToRefreshLayout pullToRefreshLayout)
        {
            pageIndex = buildList.size() / Utils.ONCECOUNT + 1;
            initData();
        }
    };

    private BuildListAdapter.ClickListener clickListener = new BuildListAdapter.ClickListener()
    {
        @Override
        public void onClick(int position)
        {
            Build build = buildList.get(position);
            Intent intent = new Intent(BuildListActivity.this, BuildTestActivity.class);
            intent.putExtra("build", build);
            intent.putExtra("type", type);
            startActivity(intent);
        }
    };

    private EnterpriseBuildListAdapter.ClickListener eClickListener = new EnterpriseBuildListAdapter.ClickListener()
    {
        @Override
        public void onClick(int position)
        {
            Build build = buildList.get(position);
            Intent intent = new Intent(BuildListActivity.this, BuildTestEnterpriseActivity.class);
            intent.putExtra("build", build);
            intent.putExtra("type", type);
            startActivity(intent);
        }
    };

    private TextWatcher textWatcher = new TextWatcher()
    {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after)
        {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count)
        {

        }

        @Override
        public void afterTextChanged(Editable s) {
            initData();
        }
    };

    @OnClick({R.id.iv_back, R.id.add})
    public void onClick(View view)
    {
        switch (view.getId())
        {
            case R.id.iv_back:
                finish();
                break;
            case R.id.add:
                Intent intent = new Intent(this, BuildAddActivity.class);
                intent.putExtra("fromEnterprise", fromEnterprise);
                startActivityForResult(intent, 1);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 1 && requestCode == 1) {
            initData();
        }
    }

    private void getBuildList(String alert)
    {
        JSONObject jsonObject = new JSONObject();
        try
        {
            if (!fromEnterprise)
            {
                jsonObject.put("constructionId", SPUtil.getString(this, "constructionid"));
            } else
            {
                jsonObject.put("constructionName", etProject.getEditableText().toString());
            }
            jsonObject.put("pageNum", pageIndex + "");

        } catch (JSONException e)
        {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try
        {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }
        Utils.requestData(alert, this, "/build/listByConstructionId/" + SPUtil.getString(this, "uuid"), params, new Utils.ListenerJson()
        {
            @Override
            public void onSuccess(String json)
            {
                if (!Utils.isEmpty(json))
                {
                    Gson gson = new Gson();
                    BuildListRes res = gson.fromJson(json, BuildListRes.class);
                    if (res.getStatus() == 1)
                    {
                        Message message = handler.obtainMessage();
                        message.obj = res.getValue();
                        message.what = Constants.UPDATE;
                        message.sendToTarget();
                    } else
                    {
                        showToast(res.getMsg());
                        if (pageIndex == 1)
                        {
                            refreshList.refreshFinish(PullToRefreshLayout.FAIL);
                        } else
                        {
                            refreshList.loadmoreFinish(PullToRefreshLayout.FAIL);
                        }
                    }
                } else
                {
                    showToast("系统异常");
                    if (pageIndex == 1)
                    {
                        refreshList.refreshFinish(PullToRefreshLayout.FAIL);
                    } else
                    {
                        refreshList.loadmoreFinish(PullToRefreshLayout.FAIL);
                    }
                }
            }

            @Override
            public void onFailure(String json)
            {
                try
                {
                    JSONObject object = new JSONObject(json);
                    String msg = object.getString("msg");
                    showToast(msg);
                } catch (JSONException e)
                {
                    e.printStackTrace();
                    showToast("系统异常");
                }
                if (pageIndex == 1)
                {
                    refreshList.refreshFinish(PullToRefreshLayout.FAIL);
                } else
                {
                    refreshList.loadmoreFinish(PullToRefreshLayout.FAIL);
                }
            }
        });
    }

    private void addBuildData(List<Build> datas)
    {
        if (pageIndex == 1)
        {
            refreshList.refreshFinish(PullToRefreshLayout.SUCCEED);
            buildList = datas;
        } else
        {
            refreshList.loadmoreFinish(PullToRefreshLayout.SUCCEED);
            buildList.addAll(datas);
        }
        if (datas.size() >= Utils.ONCECOUNT)
        {
            refreshList.setPullUpEnable(true);
        } else
        {
            refreshList.setPullUpEnable(false);
        }
        if (fromEnterprise)
        {
            eBuildListAdapter.setDataList(buildList);
        } else
        {
            buildListAdapter.setDataList(buildList);
        }
    }
}